package com.fjnu.service.impl;

import com.fjnu.annotation.ExceptionGlobalCatch;
import com.fjnu.dao.ArticleDao;
import com.fjnu.dao.UserDao;
import com.fjnu.domain.dto.ArticleConditionDto;
import com.fjnu.domain.dto.ArticleUpdateDto;
import com.fjnu.domain.entity.Article;
import com.fjnu.service.ArticleService;
import com.fjnu.domain.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

@Service
@ExceptionGlobalCatch
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleDao articleDao;

    @Autowired
    private UserDao userDao;

    @Override
    public PageResult queryByArticleCondition(ArticleConditionDto articleCond, Integer pageNum, Integer pageSize) {
        if (pageNum == null || pageNum < 1) {
            pageNum = 1;
        }
        if (pageSize == null || pageSize < 1) {
            pageSize = 10;
        }

        int startIndex = (pageNum - 1) * pageSize;

        List<Article> articleList = articleDao.selectByConditionWithLimit(articleCond, startIndex, pageSize);
        int total = articleDao.countByCondition(articleCond);
        int totalPages = (int) Math.ceil((double) total / pageSize);

        return new PageResult(articleList, total, pageNum, pageSize, totalPages);
    }

    @Override
    public Article queryById(String articleId) {
        if (articleId == null || articleId.trim().isEmpty()) {
            return null;
        }

        Integer articleIdInt = Integer.parseInt(articleId);
        return articleDao.selectById(articleIdInt);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Article insertArticle(Article article) {
        if (article == null) {
            return null;
        }

        // 设置默认值
        if (article.getStatus() == null) {
            article.setStatus(0);
        }
        if (article.getSupport() == null) {
            article.setSupport(0);
        }
        if (article.getOppose() == null) {
            article.setOppose(0);
        }
        if (article.getRecommended() == null) {
            article.setRecommended(false);
        }
        if (article.getIsTop() == null) {
            article.setIsTop(false);
        }

        int result = articleDao.insert(article);
        return result > 0 ? article : null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int publishArticle(String articleId, String userId) {
        if (articleId == null || userId == null || articleId.trim().isEmpty() || userId.trim().isEmpty()) {
            throw new IllegalArgumentException("文章ID和用户ID不能为空");
        }

        Integer articleIdInt = Integer.parseInt(articleId);
        Integer userIdInt = Integer.parseInt(userId);

        // 检查文章是否存在且属于该用户
        Article article = articleDao.selectById(articleIdInt);
        if (article == null) {
            throw new RuntimeException("文章不存在");
        }
        if (!article.getUserId().equals(userIdInt)) {
            throw new RuntimeException("文章不属于该用户");
        }

        // 如果文章已经是发布状态，直接返回成功
        if (article.getStatus() == 1) {
            return 1;
        }

        // 更新文章状态为已发布
        int updateResult = articleDao.updateStatus(articleIdInt, 1);
        if (updateResult == 0) {
            throw new RuntimeException("更新文章状态失败");
        }

        // 更新用户积分（发布一篇文章加10分）
        int scoreResult = userDao.updateScore(userIdInt, 10L);
        if (scoreResult == 0) {
            throw new RuntimeException("更新用户积分失败");
        }

        return 1;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int publishArticlesByBatch(String[] articleIds, String userId) {
        if (articleIds == null || articleIds.length == 0 || userId == null || userId.trim().isEmpty()) {
            throw new IllegalArgumentException("文章ID数组和用户ID不能为空");
        }

        Integer userIdInt = Integer.parseInt(userId);
        List<Integer> articleIdInts = Arrays.stream(articleIds)
                .map(Integer::parseInt)
                .toList();

        // 检查所有文章
        for (Integer articleId : articleIdInts) {
            Article article = articleDao.selectById(articleId);
            if (article == null || !article.getUserId().equals(userIdInt)) {
                throw new RuntimeException("文章不存在或不属于该用户");
            }
        }

        // 批量更新文章状态
        int updateResult = articleDao.batchUpdateStatus(articleIdInts, 1);
        if (updateResult != articleIds.length) {
            throw new RuntimeException("批量更新文章状态失败");
        }

        // 更新用户积分
        int scoreResult = userDao.updateScore(userIdInt, (long) (10 * articleIds.length));
        if (scoreResult == 0) {
            throw new RuntimeException("更新用户积分失败");
        }

        return 1;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateArticle(ArticleUpdateDto articleUpdateDto) {
        if (articleUpdateDto == null || articleUpdateDto.getArticleId() == null) {
            throw new RuntimeException("参数不能为空");
        }

        Integer articleId = Integer.parseInt(articleUpdateDto.getArticleId());

        ArticleConditionDto condition = new ArticleConditionDto();

        // 设置要更新的字段
        if (articleUpdateDto.getTitle() != null && !articleUpdateDto.getTitle().trim().isEmpty()) {
            condition.setTitle(articleUpdateDto.getTitle());
        }
        if (articleUpdateDto.getContent() != null && !articleUpdateDto.getContent().trim().isEmpty()) {
            condition.setContent(articleUpdateDto.getContent());
        }
        if (articleUpdateDto.getDescription() != null) {
            condition.setDescription(articleUpdateDto.getDescription());
        }
        if (articleUpdateDto.getCategoryId() != null) {
            condition.setCategoryId(articleUpdateDto.getCategoryId());
        }
        if (articleUpdateDto.getStatus() != null) {
            condition.setStatus(articleUpdateDto.getStatus());
        }

        return articleDao.updateByCondition(articleId, condition);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int removeArticle(String articleId, String userId) {
        if (articleId == null || userId == null || articleId.trim().isEmpty() || userId.trim().isEmpty()) {
            throw new IllegalArgumentException("文章ID和用户ID不能为空");
        }

        Integer articleIdInt = Integer.parseInt(articleId);
        Integer userIdInt = Integer.parseInt(userId);

        // 检查文章
        Article article = articleDao.selectById(articleIdInt);
        if (article == null || !article.getUserId().equals(userIdInt)) {
            throw new RuntimeException("文章不存在或不属于该用户");
        }

        // 先扣除积分
        if (article.getStatus() == 1) {
            int scoreResult = userDao.updateScore(userIdInt, -10L);
            if (scoreResult == 0) {
                throw new RuntimeException("扣除用户积分失败");
            }
        }

        // 再删除文章
        int deleteResult = articleDao.deleteById(articleIdInt);
        if (deleteResult == 0) {
            throw new RuntimeException("删除文章失败");
        }

        return 1;
    }
}